/**
 * 点击上传
 * **/
$(document).on("change", "#uploadFile", function () {
    if ($(this)[0].files.length) {
        //$(this).parent().next().html(($(this)[0].files)[0].name);
        $("#uploadWaiting").css("display", "block");
        var list = $(this)[0].files;
        //console.log(list[0].name);
        uploadFile($(".container").attr('uploadFilesUrl'), list[0], function (result) {
            var result = JSON.parse(result);
            if (result.status == 1000) {
                $("#CoursewareAffixAssist").val(result.uploadFileDTO.fileId);
                pptChange(result.uploadFileDTO.fileId);
                var arr = result.uploadFileDTO.fileId.split("/");
                $("#CoursewareAffixOriginalName").val(list[0].name);
                $.post($(".container").attr('storageOriginalFileNameUrl'), {
                    sNowFileName: result.uploadFileDTO.fileId,
                    sOriginalFileName: list[0].name
                }, function (result) {
                });
                $("#CoursewareAffixName").html(list[0].name + ' <strong class="deleteico" onclick="deleteCoursewareAffix()">删</strong>');
            } else {
                alert(result.message);
            }
        });
    } else {
        $(this).parent().next().html("未上传任何文件");
        $("#uploadFile").css("color", "transparent");
    }
});
//ppturl上传给服务器请求jpgurl
function pptChange(pptUrl) {
    var json = {url: pptUrl}
    var fileExtension = pptUrl.substring(pptUrl.lastIndexOf('.') + 1);
    if (fileExtension.toLowerCase() == 'cwep') {
        $("#CoursewareAffix").val(pptUrl);
        $("#uploadWaiting").css("display", "none");
        ajaxSubmit();
        return false;
    }
    ajaxUpload($(".container").attr('pptToZipUrl'), false, JSON.stringify(json), function (result) {
        if (result.status == 1000) {
            $("#CoursewareAffix").val(result.url);
            $("#uploadWaiting").css("display", "none");
            ajaxSubmit();
        }
    });
}

/**
 * 异步上传
 * @param {*请求url} url
 * @param {*是否同步} sync
 * @param {*数据对象} form
 * @param {*回调} callback
 */
function ajaxUpload(url, sync, form, callback) {
    $.ajax({
        type: "post",
        url: url,
        data: form,
        async: sync,
        dataType: "json",
        contentType: "application/json",
        success: function (result) {
            callback(result)
        },
        error: function () {
            $("#uploadWaiting").css("display", "none");
            console.log("error");
        }
    });
}

//异步提交文件
/*function uploadFile(_url, formObj, callback) {
    getFileMd5(formObj, function (md5) {
        /!* FormData 是表单数据类 *!/
        var fd = new FormData();
        var ajax = new XMLHttpRequest();
        /!* 把文件添加到表单里 *!/
        fd.append("files", formObj);
        ajax.setRequestHeader("XueHai-MD5",md5);
        ajax.open("post", _url , true);
        ajax.onload = function () {
            var result = JSON.parse(ajax.responseText).uploadFileDTO.fileId;//上传的地址
            if (JSON.parse(ajax.responseText).status === 1000) {
                callback(ajax.responseText);
            } else {
                //返回失败
                callback('{status:2000,message:"失败了!"}');
                // callback(ajax.responseText);
            }
            $(".wait").css("display", "none");
        };
        ajax.send(fd);
    });
}


//将文件名转换为md5格式
function getFileMd5(file, callback) {
    var md5 = "";
    var fileReader = new FileReader();
    fileReader.onload = function (e) {
        if (file.size = e.target.result.length) {
            md5 = SparkMD5.hashBinary(e.target.result).toUpperCase();
            callback(md5);
        }
    };
    fileReader.readAsBinaryString(file);
}*/
//异步提交文件
function uploadFile(_url, formObj, callback) {
    getFileMd5(formObj, function (md5) {
        /* FormData 是表单数据类 */
        var fd = new FormData();
        var ajax = new XMLHttpRequest();
        /* 把文件添加到表单里 */
        fd.append("files", formObj);
        ajax.open("post", _url + md5, true);
        ajax.setRequestHeader("XueHai-MD5",md5);
        ajax.onload = function () {
            // var result = JSON.parse(ajax.responseText).uploadFileDTO.fileId;
            console.log(_url);
            console.log(JSON.parse(ajax.responseText).status);
            if (JSON.parse(ajax.responseText).status == "1000") {
                callback(ajax.responseText);
            } else {
                //返回失败
                callback('{status:2000,message:"失败了!"}');
            }
            $(".wait").css("display", "none");
        };
        ajax.send(fd);
    });

}

function uploadFileToServer(file, callback) {
    var fileData = new FormData();
    fileData.append('file', file);
    $.ajax({
        url: moduleUrl + 'Service/uploadFile',
        type: 'POST',
        processData: false,
        contentType: false,
        data: fileData,
        complete: function(XMLHttpRequest){
            var result = XMLHttpRequest.responseJSON;
            callback(result);
            $(".wait").css("display", "none");

        }
    });
}


//将文件名转换为md5格式
function getFileMd5(file, callback) {
    var md5 = "";
    var fileReader = new FileReader();
    fileReader.onload = function(e) {
        if (file.size = e.target.result.byteLength) {
            var bytes = new Uint8Array(fileReader.result);
            var length = bytes.byteLength;
            var binary = '';
            for (var i = 0; i < length; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            md5 = SparkMD5.hashBinary(binary).toUpperCase();
            callback(md5);
        }
    };
    fileReader.readAsArrayBuffer(file);
}





